package com.curry.log.file;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * 将对象转成JSON字符串
 * 
 * @author chenxiang
 */
public class JSONHelper {

	public static final int ACT_NO_HRED = 0;
	public static final int ACT_OFF_HRED = 1;
	/**
	 * javaBean转JSON
	 * @param 对象
	 * @param type
	 * @return
	 * @throws Exception
	 */

	public static String bean2json(Object o, int type) throws Exception {
		Class c = o.getClass();
		StringBuffer sb = new StringBuffer();
		try {

			Field[] fields = c.getDeclaredFields();
			Method[] methods = c.getDeclaredMethods();

			for (Field f : fields) {
				System.out.println("字段:" + f.getName());
			}
			for (Method method : methods) {
				String m = method.getName();
				if (m.contains("get")&&!m.contains("getClass")) {
					sb.append(",");
					sb.append("\"" + NameChange(m) + "\"");
					sb.append(":");
					Object obj = method.invoke(o);
					if (obj instanceof Integer) {
						sb.append(String.valueOf(obj));
					} else if (obj == null) {
						sb.append(obj);
					} else {
						sb.append("\"" + obj + "\"");
					}

				}

			}
			String json = null;
			if (type == ACT_NO_HRED) {
				json = "\"" + c.getSimpleName().toLowerCase() + "\":{"
						+ sb.toString().substring(1) + "},";
			} else {
				json = ",{" + sb.toString().substring(1) + "}";
			}
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	/**
	 * javaBean转JSON
	 * @param c  类对象
	 * @return
	 * @throws Exception
	 */
	public static String bean2json(Class c) throws Exception{
		String patch=c.getPackage()+c.getSimpleName();
		StringBuffer sb=new StringBuffer();
		Class demo;
		try {
			demo = Class.forName(patch);
			  Field[] fields=demo.getDeclaredFields();
			     Method[] methods=demo.getDeclaredMethods();
			     
			     for(Field f:fields){
			      System.out.println("字段:"+f.getName());
			     }
			     for(Method method:methods){
			       String m=method.getName();
			       
			       
			       if( m.contains("get")){
			    	   sb.append("\""+NameChange(m)+"\"");
			    	   sb.append(":");
			    	   Object obj=method.invoke(demo);
			    	   if(obj instanceof Integer){
			    		   sb.append(String.valueOf(obj));
			    	   }else{
			    		   sb.append("\""+obj+"\"");
			    	   }
				   }
			       sb.append(",");
			    }
			  String json="\""+ c.getSimpleName().toLowerCase()+"\":{"+sb.toString()+"}";  
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static String NameChange (String str){
		String name=str.substring(str.indexOf("get") + 3);
		String head=name.substring(0, 1).toLowerCase();
		return head+name.substring(1);
	}
}
